function SPM = AncovaTest(swPETPath, logHandle)
% 31/03/2010
% Author : Ernest Galbrun

databaseFolder = [cd filesep 'DB' filesep];
% test ANCOVA :
%  D = struct('DesName','Compare-populations: 1 scan/subject (AnCova)',...
%             'n',[Inf 2 1 1],	'sF',{{'subject','group','',''}},...
%             'Hform',		'I(:,2),''-'',''group''',...
%             'Bform',		'I(:,3),''-'',''\mu''',...
%             'nC',[0,Inf],'iCC',{{8,1}},'iCFI',{{1,1}},...
%             'iGXcalc',[1,2,-3],'iGMsca',[-1,9],'GM',50,...
%             'iGloNorm',[1,8,9],'iGC',10,...
%             'M_',struct('T',[0,0.8*sqrt(-1)],'I',0,'X',0),...
%             'b',struct('aTime',0));

maxAgeDifference = 10; 
% Retrieve age of current patient
n=strfind(swPETPath,'_');
nAgeDigits = length(swPETPath)-n(end)-4;
age=str2num(swPETPath(end-3-nAgeDigits:end-4));
    
DBFile=[databaseFolder 'DB.txt'];
    nAttributes=3;   
    DBFields=textread(DBFile,'%s','whitespace','','delimiter','\t');  
    ageArray = age;   
    pathArray(1) = {[swPETPath ',1']};
    
    % Get path and age of reference .nii files.
    % Stored in two arrays named ageArray and pathArray.
    % The first element of both is age and path for studied patient.
    % maxAgeDifference is increased as long as there are less than 2 
    % reference healthy patients.
    while length(ageArray)<6
        for i=1:nAttributes:length(DBFields)
            fileName=DBFields{i};
            % Check if the reference patient is healthy (='sain').
            if strcmp(DBFields{i+2},'sain')
                % Check that the difference of age is ok.
                if (str2num(DBFields{i+1}) >= age - maxAgeDifference)...
                        && (str2num(DBFields{i+1}) <= age + maxAgeDifference)
                    pathArray=[pathArray;fullfile(databaseFolder, fileName(1:6),...
                        ['sw' fileName '.nii,1'])];
                    ageArray=[ageArray;str2num(DBFields{i+1})];
                end
            end
        end
        maxAgeDifference = maxAgeDifference + 1;
    end
    
message = [num2str(length(ageArray)) ' healthy patient found whose age difference with current patient is less than ' num2str(maxAgeDifference) ' year.'];
set(logHandle,'string',[{message};(get(logHandle,'string'))]);
% Creates SPM.mat
SPM = CIATstats (pathArray, ageArray);
%load('SPM'); 
currentFolder = cd;
% Remove mask file to prevent spm from prompting for writing over existing
% file
if exist(fullfile(SPM.swd,'mask.img'),'file') == 2;
    delete(fullfile(SPM.swd,'mask.img'));
    try, SPM = rmfield(SPM,'xVol'); end
end;

SPM = spm_spm(SPM); % use SPM.mat to compute results
cd (currentFolder);

